package com.joinway.mobile.service

import org.json.JSONArray
import org.json.JSONObject

import com.joinway.common.bean.domain.custom.GoodProperty
import com.joinway.framework.data.jdbc.repository.TableRepository
import com.joinway.framework.ecshop.bean.constant.DomainConstants
import com.joinway.framework.ecshop.bean.domain.Cart
import com.joinway.framework.ecshop.bean.domain.Good
import com.joinway.framework.ecshop.bean.domain.GoodGallery
import com.joinway.framework.ecshop.bean.domain.OrderGood
import com.joinway.framework.ecshop.bean.domain.OrderInfo
import com.joinway.mobile.bean.Product
import com.joinway.mobile.bean.ProductAttribute
import com.joinway.mobile.bean.ProductProperty
import com.joinway.mobile.bean.form.OrderForm
import com.joinway.mobile.bean.form.ShopCart
import com.joinway.mobile.bean.view.OrderProduct
import com.joinway.mobile.bean.view.ShopCartProduct
import com.joinway.mobile.constants.AppConstants
import com.joinway.mobile.exception.MobileErrorConstants
import com.joinway.mobile.exception.MobileException

class JiayidaServiceSupport {

	protected TableRepository repository;
	protected String tablePrefix;
	protected SqlFactory factory
	
	public JiayidaServiceSupport(String tablePrefix, TableRepository repository){
		this.tablePrefix = tablePrefix
		this.repository = repository
		factory = new SqlFactory(tablePrefix)
	}
	
	public List<Product> getProducts(Integer catId, int page, int rows){
		List<Product> products //= new ArrayList<>();
//		List<Good> goods
		
//		String sql = "select * from ${tablePrefix}_goods"
		if(AppConstants.TablePrefix.Baby.equalsIgnoreCase(tablePrefix)){
			String sql = factory.createFindPruductSql(catId)
			products = repository.find(sql, Product, page, rows, catId)
		}else{
			String sql = factory.createFindPruductSql()
			products = repository.find(sql, Product, page, rows)
		}
		
//		if(goods){
//			goods.each{products.add(buildProduct(it))}
//		}
		
		return products;
	}

	public Product getProductDetail(int id) throws Exception {
		String sql = factory.createFindPruductSql(null, id)
//		Good good = repository.findById(Good, id, "${tablePrefix}_goods")
		def (domain) = repository.find(Product, sql, id)
		
		Product product = (Product)domain
		
		sql = """
		SELECT DISTINCT 
			BGA.goods_attr_id attrId
			, BA.attr_name name
			, BGA.attr_value value
			FROM ${tablePrefix}_attribute BA
				LEFT JOIN ${tablePrefix}_goods_attr BGA ON BA.attr_id = BGA.attr_id
				RIGHT JOIN ${tablePrefix}_goods BG ON BGA.goods_id = BG.goods_id
		WHERE BG.goods_id = ?
		ORDER BY BGA.attr_id	
"""
		List<GoodProperty> gps = repository.find(GoodProperty, sql, id)
		
		Map<String, List<ProductProperty>> ppMap = new HashMap<>();
		if(gps){
			for(GoodProperty p : gps){
				if(p != null){
					List<ProductProperty> pps = ppMap.get(p.getName());
					
					if(pps == null){
						pps = new LinkedList<>();
						ppMap.put(p.getName(), pps);
					
						ProductProperty pp = new ProductProperty();
						pp.setName(p.getName());
						pp.getAttributes().add(new ProductAttribute(p.getAttrId(), p.getValue()));
						
						pps.add(pp);
					}else{
						ProductProperty pp = pps.find {p.getName().equalsIgnoreCase(it.getName())}
						if(pp){
							pp.getAttributes().add(new ProductAttribute(p.getAttrId(), p.getValue()));
						}
					}
					
					
				}
			}
		}
		
		if(ppMap.size() > 0){
			List<ProductProperty> pps = new LinkedList<>();
			ppMap.values().each {pps.addAll(it)}
			product.setProperties(pps);
		}
		
		return product;
	}
	
	public List<OrderProduct> getOrderedProducts(int userId, int page, int rows){
		String sql = """
		SELECT 
			BG.goods_id	id
			, BG.goods_name	name
			, BG.shop_price	price
			, BOG.goods_number	count
			, BOG.goods_attr property
			, BG.goods_thumb photos
		 FROM ${tablePrefix}_goods BG 
			RIGHT JOIN ${tablePrefix}_order_goods BOG ON BG.goods_id = BOG.goods_id 
			RIGHT JOIN ${tablePrefix}_order_info BOI ON BOI.order_id = BOG.order_id
		WHERE BOI.user_id = ?
"""
		repository.find(sql, OrderProduct, page, rows, userId)
	}
	
	public List<ShopCartProduct> getShopCartProduct(int userId, int page, int rows){
		String sql = """
		SELECT 
			bg.goods_id id
			, bg.goods_name	name
			, bg.shop_price	price
			, bc.goods_number	count
			, bc.goods_attr	property
			, bc.rec_id	cartId
			, bg.goods_thumb photos
		 from ${tablePrefix}_goods bg 
			right join ${tablePrefix}_cart bc on bg.goods_id = bc.goods_id 
		WHERE bc.user_id = ?
"""
		repository.find(sql, ShopCartProduct, page, rows, userId)
	}

	public void addShopCart(int userId, int pid, String propId, int number){
		Good good = repository.findById(Good, pid, "${tablePrefix}_goods")
		
		// 查看商品数量
		int remains = good.getGoodsNumber() - number
		if(remains < 0){
			throw new MobileException(MobileErrorConstants.NOT_ENOUGH_GOOD)
		}
		
		// 如果已经购买过同类型商品，增加数量
		List<ShopCart> carts = repository.find(ShopCart, "select * from ${tablePrefix}_cart where goods_id = ? and user_id = ?", pid, userId)
		
		Cart cart = carts ? carts[0] : null
		if(cart){
			cart.setGoodsNumber(cart.getGoodsNumber() + number)
		}else{
			cart = new Cart()
			cart.setUserId(userId);
			cart.setGoodsId(pid);
			cart.setIsReal(1)
			cart.setGoodsSn(good.getGoodsSn());
			cart.setGoodsName(good.getGoodsName());
			cart.setMarketPrice(good.getMarketPrice());
			cart.setGoodsPrice(good.getShopPrice());
			cart.setGoodsNumber(number);
			cart.setGoodsAttrId(propId);
		}
		
		repository.save(cart, "${tablePrefix}_cart")
	}
	
	public void updateShopCart(int cartId, int number) {
		Cart cart = repository.findById(Cart, cartId, "${tablePrefix}_cart")
		if(!cart){
			throw new MobileException(MobileErrorConstants.NO_SUCH_GOOD_IN_CART)
		}
		
		cart.setGoodsNumber(number);
		
		repository.save(cart, "${tablePrefix}_cart")
	}

	public void deleteShopCart(int cartId){
		repository.delete("delete from ${tablePrefix}_cart where rec_id = ?", cartId)
	}

	@Deprecated public void addOrder(String orderStr, String goodsList, String cartIds) {
		JSONObject jsonObject = new JSONObject(orderStr);
		OrderInfo jdyagriOrder = new OrderInfo();
		jdyagriOrder.setOrderSn(jsonObject.getString("orderSn"));
		jdyagriOrder.setUserId(jsonObject.getString("userId"));
		jdyagriOrder.setOrderStatus(jsonObject.getString("orderStatus"));
		jdyagriOrder.setShippingStatus(jsonObject.getString("shippingStatus"));
		jdyagriOrder.setPayStatus(jsonObject.getString("payStatus"));
		jdyagriOrder.setConsignee(jsonObject.getString("consignee"));
		jdyagriOrder.setPayId(jsonObject.getString("payId"));
		jdyagriOrder.setPayName(jsonObject.getString("payName"));
		jdyagriOrder.setPayFee(jsonObject.getString("payFee"));
		jdyagriOrder.setGoodsAmount(jsonObject.getString("goodsAmount"));
		jdyagriOrder.setAddress(jsonObject.getString("address"));
		jdyagriOrder.setTel(jsonObject.getString("telephone"));
		jdyagriOrder.setMobile(jsonObject.getString("telephone"));
		jdyagriOrder.setAgencyId("0");
		jdyagriOrder.setInvType("1");
		jdyagriOrder.setTax("0.00");
		jdyagriOrder.setDiscount("0");
		
		//保存订单信息
		repository.save(jdyagriOrder, "${tablePrefix}_order_info");
		
		String orderId = jdyagriOrder.getOrderId();
		
		List<OrderGood> list = new ArrayList<OrderGood>();
		JSONArray jsonArray = new JSONArray(goodsList);
		for(int i = 0; i < jsonArray.length(); i++){
			JSONObject orderGoods = jsonArray.getJSONObject(i);
			OrderGood jdyagriOrderGoods = new OrderGood();
			jdyagriOrderGoods.setOrderId(orderId);
			jdyagriOrderGoods.setGoodsId(orderGoods.getString("goodsId"));
			jdyagriOrderGoods.setGoodsName(orderGoods.getString("goodsName"));
			jdyagriOrderGoods.setGoodsNumber(orderGoods.getString("goodsNumber"));
			jdyagriOrderGoods.setGoodsPrice(orderGoods.getString("goodsPrice"));
			jdyagriOrderGoods.setGoodsAttr("无");
			list.add(jdyagriOrderGoods);
		}
		
		Iterator<OrderGood> iterator = list.iterator();
		while(iterator.hasNext()){
			//保存订单商品信息
			repository.save(iterator.next(), "${tablePrefix}_order_goods");
		}
		
		//删除购物车已经结算过的商品信息
		JSONArray cartIdJSONArray = new JSONArray(cartIds);
		for(int i = 0; i < cartIdJSONArray.length(); i++){
			int cartId = cartIdJSONArray.getInt(i);
			repository.delete("delete from ${tablePrefix}_cart where rec_id = ?", cartId)
		}
	}

	public void createOrder(OrderForm form) throws Exception{
		List ids = []
		form.carts.each{
			ids << it.cartId
		}
		String cartIds = ids.iterator().join(",")
		
		List<Cart> carts = repository.find(Cart, "select * from ${tablePrefix}_cart where rec_id in ($cartIds)")
//		User user = repository.findById(User, userOrder.userId, "${tablePrefix}_users")
//		def (domain) = repository.find(UserAddress, "select * from ${tablePrefix}_user_address where user_id = ?", userOrder.userId)
//		UserAddress address = (UserAddress)domain;
//		String userName = address ? address.consignee : user.userName
		
		OrderInfo orderInfo = new OrderInfo()
		orderInfo.orderSn = form.orderId
		orderInfo.userId = form.userId
		orderInfo.orderStatus = DomainConstants.Order.OrderStatus.Confirmed
		orderInfo.payStatus = DomainConstants.Order.PayStatus.Paid
		
		// TODO set to Dalian for now
		orderInfo.consignee = form.consignee
		orderInfo.country = 1
		orderInfo.province = 18
		orderInfo.city = 245
		orderInfo.district = 2075
		orderInfo.address = form.address
		orderInfo.zipcode = form.zip
		orderInfo.tel = form.tel
//		orderInfo.mobile = address.mobile
//		orderInfo.bestTime = address.bestTime
//		orderInfo.signBuilding = address.signBuilding
		// TODO shipping
		orderInfo.shippingId = 1
		
		// TODO payment
		orderInfo.payId = 1
		orderInfo.payName = '手机支付'
		
		double cost = 0
		form.carts.each{
			cost += it.cost
		}
		orderInfo.goodsAmount = cost
		orderInfo.orderAmount = cost
		orderInfo.moneyPaid = cost
		
		orderInfo = repository.save(orderInfo, "${tablePrefix}_order_info");
		
		//保存订单商品信息
		carts.each {
			Cart cart = it
			ShopCart shopCart = form.carts.find {it.cartId == cart.recId}
			
			OrderGood orderGood = new OrderGood()
			
			orderGood.orderId = orderInfo.orderId
			orderGood.goodsId = it.goodsId
			orderGood.goodsName = it.goodsName
			orderGood.goodsSn = it.goodsSn
			orderGood.goodsNumber = shopCart.amount
			orderGood.goodsPrice = shopCart.cost
			orderGood.goodsAttr = it.goodsAttr
			orderGood.isReal = it.isReal
			orderGood.extensionCode = it.extensionCode
			orderGood.isGift = it.isGift
			
			orderGood.goodsAttrId = it.goodsAttrId
			
			repository.save(orderGood, "${tablePrefix}_order_goods")
		}
		
		//删除购物车已经结算过的商品信息
		repository.delete("delete from ${tablePrefix}_cart where rec_id in ($cartIds)")
	}
	
	@Deprecated protected Product buildProduct(Good good){
		Product product = new Product();
		product.setName(good.getGoodsName());
		product.setPrice(good.getShopPrice());
		product.setId(good.getGoodsId());

		List<GoodGallery> ggs = repository.find("select * from ${tablePrefix}_goods_gallery where goods_id = ?", good.getGoodsId());
		//查询商品缩略图（一条记录）
		String photos = "";
		if(ggs != null && ggs.size() > 0){
			photos = ggs.get(0).getThumbUrl();
		}
		product.setPhotos(photos);

		return product;
	}
}
